package net.youball.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import net.youball.conf.entity.Location;
import net.youball.conf.entity.XY;

public class LocationUtils {
	
	private static final double EARTH_RADIUS=6378137.0;
	 public static double getDistance(double lat1, double lon1, double lat2, double lon2){  
			double radLat1 = lat1 * Math.PI / 180;  
			double radLat2 = lat2 * Math.PI / 180;  
			double a = radLat1 - radLat2;  
			double b = lon1 * Math.PI / 180 - lon2 * Math.PI / 180;  
			double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)  
			        + Math.cos(radLat1) * Math.cos(radLat2)  
			       * Math.pow(Math.sin(b / 2), 2)));  
			s = s * EARTH_RADIUS;// 
			s = Math.round(s * 10000) / 10000;  
			return s;  
	}  
	 
	 
	@SuppressWarnings("unchecked")
	public static  List<Location> getLocation(XY xy){
		//ServletContext app= XFireServletController.getRequest().getSession().getServletContext();
		ServletContext app=ServletActionContext.getServletContext();
		Map<XY,List<Location>>  local=(Map<XY, List<Location>>) app.getAttribute("location");
		
		return local.get(xy);
	
	}
	@SuppressWarnings("unchecked")
	public static Map<XY,List<Location>> setLocation(XY xy,Location obj){
		//ServletContext app= XFireServletController.getRequest().getSession().getServletContext();
		ServletContext app=ServletActionContext.getServletContext();
		Map<XY,List<Location>>  local=(Map<XY, List<Location>>) app.getAttribute("location");
		List<Location> list=local.get(xy);
		if(list!=null&&list.size()!=0){
			list.add(obj);
		}else{
			list=new ArrayList<Location>();
			list.add(obj);
		}
		local.put(xy, list);
		System.out.println(local);
		app.setAttribute("location", local);
		return local;
		
	}
	public static Integer getXYFirst(String doubleString){
		Integer first=0;
		if(doubleString.indexOf(".")!=-1){
		String x=doubleString.substring(0,doubleString.indexOf("."));
			first=Integer.parseInt(x);
		}else{
			first=Integer.parseInt(doubleString);
		}
		
		return first;
	}
	public static Integer getXYLast(String doubleString){
		Integer last=0;
		if(doubleString.indexOf(".")!=-1){
			String x=doubleString.substring(doubleString.indexOf(".")+1);
			last=Integer.parseInt(x);
		}
		
		return last;
	}
}
